import React, { useEffect, useRef, useState } from 'react';
import { Button, Table, Modal, Switch, message} from 'antd';
import API from '../../../util/api';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import UserForm  from '../../../components/user-manage/UserForm';
const { confirm } = Modal;


export default function UserList() {
    const [dataSource, setdataSource] = useState([]);
    const [isAddVisible, setisAddVisible] = useState(false);
    const [isUpdateVisible, setisUpdateVisible] = useState(false);
    const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
    const [roleList, setroleList] = useState([]);
    const [regionList, setregionList] = useState([]);
    const [current, setcurrent] = useState(null);
    const addFormRef = useRef(null);
    const updateFormRef = useRef(null);
    const {roleId,region,username}  = JSON.parse(localStorage.getItem("token"));

    useEffect(() => {
        const roleObj = {
            "1":"superadmin",
            "2":"admin",
            "3":"editor"
        }
        API.login({_expand: 'role'}).then(res => {
            const list = res.data
            setdataSource(roleObj[roleId]==="superadmin"? list:[
                ...list.filter(item=>item.username===username),
                ...list.filter(item=>item.region===region && roleObj[item.roleId]==="editor")
            ]);
        })
    }, [roleId,region,username]);


    useEffect(() => {
        API.regions().then(res => {
            const list = res.data;
            setregionList(list);
        })
    }, []);

    useEffect(() => {
        API.roles().then(res => {
            const list = res.data;
            setroleList(list);
        });
    }, []);
    const columns = [
        {
            title:'序号',
            dataIndex: 'id',
            align: 'center',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title:'区域',
            dataIndex: 'region',
            align: 'center',
            filters: [
                ...regionList.map(item=>({
                    text:item.title,
                    value:item.value
                })),
                {
                    text:"全球",
                    value:"全球"
                }    

            ],
            onFilter:(value,item)=>{
                if(value==="全球"){
                    return item.region===""
                }
                return item.region===value
            },
          
            render: (region) => {
                return <b>{region === '' ? '全球' : region}</b>
            }
        },
        {
            title:'角色名称',
            dataIndex: 'role',
            align: 'center',
            render: (role) => {
                return role.roleName
            }
        },
        {
            title:'用户名',
            dataIndex: 'username',
            align: 'center'
        },
        {
            title:'用户状态',
            dataIndex: 'roleState',
            align: 'center',
            render: (roleState, item) => {
                return <Switch checked={roleState} disabled={item.default} onChange={ () => switchMethod(item)}></Switch>
            }
        },
        {
            title:'操作',
            align: 'center',
            render: (item) => {
                return <div>
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} disabled={item.default}/>
                    <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={ () => handleUpdate(item)}/>
                </div>
            }
        }
    ]
    // 切换状态
    const switchMethod = (item) => {
        item.roleState = !item.roleState;
        setdataSource([...dataSource]);
        API.changeStatus(item.id, { roleState:item.roleState }).then(res => {
            if (res.status === 200) {
                message.success('状态切换成功');
            }
        })
    }
    const confirmMethod = (item) => {
        confirm({
            title: '确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                deleteMethod(item);
            },
            onCancel() {

            }
        });
    }
    // 删除
    const deleteMethod = (item) => {
        setdataSource(dataSource.filter(data => data.id !== item.id));
        API.delUser(item.id).then(res => {
            if (res.status === 200) {
                message.success('删除成功');
            } else {
                message.error(res.statusText);
            }
        });
    }
    // 添加
    const addFormOK = () => {
        addFormRef.current.validateFields().then(value => {
            setisAddVisible(false);
            addFormRef.current.resetFields();
            API.addUser({
                ...value,
                "roleState": true,
                "default": false
            }).then(res => {
                message.success('添加成功');
                setdataSource([...dataSource,{
                    ...res.data,
                    role: roleList.filter(item => item.id === value.roleId)[0]
                }]);
            }).catch(err => {
                message.error(err);
            })
        });
    }
    // 关闭
    const closeModal = () => {
        addFormRef.current.resetFields();
        setisAddVisible(false);
    }
    // 打开修改对话框并赋值
    const handleUpdate = (item) => {
        setTimeout(()=>{
            setisUpdateVisible(true);
            if(item.roleId===1){
                //禁用
                setisUpdateDisabled(true);
            }else{
                //取消禁用
                setisUpdateDisabled(false);
            }
            updateFormRef.current.setFieldsValue(item); //表单赋值
        },0);
        setcurrent(item.id);
    }
    // 修改
    const updateFormOK = () => {
        updateFormRef.current.validateFields().then(value => {
            setisUpdateVisible(false);
            setdataSource(dataSource.map(item => {
                if (item.id === current) {
                    return {
                        ...item,
                        ...value,
                        role:roleList.filter(data => data.id === value.roleId)[0]
                    }
                }
                return item;
            }));
            setisUpdateDisabled(!isUpdateDisabled);
            API.modifyUser(current, value).then(res => {
                if (res.status === 200) {
                    message.success('修改成功');
                }
            })
        });
    }
    return (
        <div>
            <Button type="primary" onClick={ () => {setisAddVisible(true)} } style={{margin: '20px 20px'}}>添加用户</Button>
            <Table  dataSource={dataSource} 
                    columns={columns}
                    rowKey={item=>item.id}
                    bordered>
            </Table>
            <Modal  visible={isAddVisible}
                    title='添加用户'
                    okText='确定'
                    cancelText='取消'
                    onCancel={ () => {closeModal()} }
                    onOk={ () => {addFormOK()} } >
                        <UserForm regionList={regionList} roleList={roleList} ref={addFormRef}></UserForm>
            </Modal>
            <Modal  visible={isUpdateVisible}
                    title="修改用户信息"
                    okText='更新'
                    cancelText='取消'
                    onCancel={ () => { 
                        setisUpdateVisible(false)
                        setisUpdateDisabled(!isUpdateDisabled)
                    } }
                    onOk={ () => {updateFormOK()} }>
                    <UserForm regionList={regionList} roleList={roleList} ref={updateFormRef} isUpdateDisabled={isUpdateDisabled}></UserForm>
            </Modal>
        </div>
    )
}